import express from 'express'
// import dayjs from 'dayjs'

const router = express.Router()
// const djs = dayjs()

let app
let client

const resObj = { code: 500, message: '失败', data: {} }

const result = (code, message, data) => {
  resObj.code = code
  resObj.message = message
  resObj.data = data || {}
}

const send = (res) => {
  res.send(resObj)
}

const genId = () => {
  return (Math.random() + new Date().getTime()).toString(32).slice(0, 8)
}

let EXP_KEY = 'ex:username'

const expKey = (username) => {
  EXP_KEY = `ex:${username}`
  return EXP_KEY
}

router.get('/:username/:day', async (req, res) => {
  const { username, day } = req.params
  EXP_KEY = `ex:${username}`
  const have = await client.hExists(EXP_KEY, day)
  if (have) {
    const arr = JSON.parse(await client.hGet(EXP_KEY, day))
    if (arr.length > 0) result(200, '查询成功', arr)
    else result(404, '暂无数据', { username, day })
  } else result(404, '暂无数据', { username, day })
  res.send(resObj)
})

router.post('/', async (req, res) => {
  const { username, day, info } = req.body
  const _id = genId()
  info._id = _id
  let r = 0
  try {
    const have = await client.hExists(expKey(username), day)
    if (have) {
      // 当天已存在报销数据
      const arr = JSON.parse(await client.hGet(EXP_KEY, day))
      if (arr) {
        r = arr.unshift(info)
        await client.hSet(EXP_KEY, day, JSON.stringify(arr))
      }
    } else {
      // 当天不存在报销数据
      r = await client.hSet(EXP_KEY, day, JSON.stringify([info]))
    }
  } catch (error) {
    result(500, '失败', error.message)
  } finally {
    if (r >= 1) result(200, '新增报销成功', { _id })
    else result(500, '新增报销失败')
    send(res)
  }
})

router.put('/', async (req, res) => {
  const { username, day, info } = req.body
  const { _id } = info
  const arr = JSON.parse(await client.hGet(expKey(username), day))
  const idx = arr.findIndex(item => item._id === _id)
  const newArr = arr.filter(item => item._id !== _id)
  newArr.splice(idx, 0, info)
  await client.hSet(EXP_KEY, day, JSON.stringify(newArr))
  if (idx >= 0) result(200, '修改报销成功')
  else result(500, '修改报销失败', { _id })
  send(res)
})

router.delete('/', async (req, res) => {
  const { username, day, _id } = req.body
  const arr = JSON.parse(await client.hGet(expKey(username), day))
  const r = arr.find(a => a._id === _id)
  const newArr = arr.filter(a => a._id !== _id)
  await client.hSet(EXP_KEY, day, JSON.stringify(newArr))
  if (r) result(200, '删除报销成功', r)
  else result(500, '删除报销失败', _id)
  send(res)
})

export default (_app, _client) => {
  app = _app
  client = _client
  return router
}
